//
//  AppDelegate.m
//  LazyCat
//
//  Created by zhanshu on 15/9/7.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "AppDelegate.h"
#import "GuideView.h"
#import "BaseTabBarViewController.h"
//#import <BaiduMapAPI/BMapKit.h>//引入所有的头文件
#import "SelectNearProprieterController.h"
#import "LoginViewController.h"
#import "AFNetworkHandler.h"
#import "MyViewController.h"

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

//以下是腾讯QQ和QQ空间
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>

#import "WXApi.h"
#import "WeiboSDK.h"
#import <sys/utsname.h>
#import <ShareSDK/ShareSDK.h>
#import "OrderViewController.h"
#import "BossMessagVC.h"

#import "GeTuiSdk.h"

#import "PlaySoundYM.h"//铃声

// AppStore
//#define kAppId           @"0kIvlriyoa5DUkLZDVLW7"
//#define kAppKey          @"DrRMHktxdyAZgdXGdUH487"
//#define kAppSecret       @"ipQUXZtZ2r5lY0e2s9chq3"

// 企业版
//#define kAppId           @"5gzwKVqYJS9PGymcKdNUx8"
//#define kAppKey          @"Z8al1TyV9U8idHUSMYnHF4"
//#define kAppSecret       @"ZPZwPiJfYyALhcN23NHDZ"

// 推送测试
//#define kAppId           @"yzIv0YGotB9aRHP7PPcg2"
//#define kAppKey          @"kyUQzudgfhADAtwEYqco56"
//#define kAppSecret       @"VwUPKPKwlW5aPl17Eofws6"

@interface AppDelegate ()<GeTuiSdkDelegate,UIAlertViewDelegate>
{
    NSInteger count;
    GuideView *guideView;
}
@property (strong, nonatomic) BaseTabBarViewController *tabVC;
@property (nonatomic) BOOL tap;
@property (nonatomic, assign) NSInteger alertCount; // 提示框弹出的次数

@end

@implementation AppDelegate
- (void)initShare {
    /*
     懒猫社长(微信)
     AppID：wxf47d1a9677116820
     AppSecret：8be5272612bf70f8f503cf7284c692ae
     wxf47d1a9677116820,tencent1105050097,QQ41DDB9F1,wb1273883023
     微博
     App Key：1273883023
     App Secret：53ecf8c10d02b911eb7972fc8dc73b08
     懒猫社长(QQ)
     APPID 1105050097
     APPKEY  nnMLtyalX2hucpXt
     */
    
    [ShareSDK registerApp:@"e95a23fed3e8"];
    [ShareSDK connectSinaWeiboWithAppKey:@"1273883023"
                               appSecret:@"53ecf8c10d02b911eb7972fc8dc73b08"
                             redirectUri:@"http://www.sharesdk.cn"
                             weiboSDKCls:[WeiboSDK class]];
    [ShareSDK connectQZoneWithAppKey:@"1105050097"
                           appSecret:@"nnMLtyalX2hucpXt"
                   qqApiInterfaceCls:[QQApiInterface class]
                     tencentOAuthCls:[TencentOAuth class]];
    [ShareSDK connectWeChatWithAppId:@"wxf47d1a9677116820"
                           appSecret:@"8be5272612bf70f8f503cf7284c692ae"
                           wechatCls:[WXApi class]];
    [ShareSDK connectQQWithQZoneAppKey:@"1105050097"
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    [ShareSDK connectCopy];
}
- (void)registerRemoteNotification {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:uns];
    }
    else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    }
    // [1]:使用APPID/APPKEY/APPSECRENT创建个推实例
    [self startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
    // [2]:注册APNS
    //    [self registerRemoteNotification];
}
- (NSString*)deviceVersion {// 获取手机型号   // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    return deviceString;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self initShare];
    count = 0;
    self.alertCount = 0;
    //vB3d3HhCgAn7oiOgXPPbdO3j   com.zhanshu.lazycat
    //AMvNvxUstmO9ecdzzyXGtxog   com.zhan.push1
    //lf2SVe6g0Xj0sh4OLdzMVM5l   com.zskj.lichuan
    // 百度地图
    //    _mapManager = [[BMKMapManager alloc]init];
    //    BOOL ret = [_mapManager start:@"lf2SVe6g0Xj0sh4OLdzMVM5l" generalDelegate:nil];
    //    if (!ret) {
    //        NSLog(@"manager start failed!");
    //    }
    BOOL doFirst = ![[NSUserDefualManager getValueByKey:@"DoFirstLogin"] boolValue];
    [AppData share].doFirst = doFirst;
    
    _tabVC = [[BaseTabBarViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:_tabVC];
    nav.navigationBarHidden = YES;
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    // 第一次登陆
    NSString *login = [NSUserDefualManager getValueByKey:@"doLogin"];
    if ([login isEqualToString:@"1"]) {
        self.window.rootViewController = nav;
    }else{
        LoginViewController *login = [[LoginViewController alloc] init];
        self.window.rootViewController = login;
    }
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    NSLog(@"手机系统版本: %@", phoneVersion);
    NSString *xh = [self deviceVersion];
    NSLog(@"手机型号：%@",xh);
    //设备名称
    NSString* deviceName = [[UIDevice currentDevice] systemName];
    NSLog(@"设 备名称: %@",deviceName );
    NSString *ipos = [deviceName stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *phone = [NSString stringWithFormat:@"%@%@,%@",ipos,phoneVersion,xh];
    NSString *stringStr = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"%@",stringStr);
    NSUserDefaults *iponeType = [NSUserDefaults standardUserDefaults];
    [iponeType setObject:stringStr forKey:@"iptype"];
    
    // 如果AppStore 版本值为:AppStore.IOS1.0.2
    // 如果企业版 版本值为:IOS1.0.2
    // 企业版越过1.0.3
    [iponeType setObject:banBen forKey:@"banben"];
    
    //定位
    //    [self locationPart];
    //监听网络
    [self theNetWorkConnectStates];
    //通知
    [self registerRemoteNotification];
    self.tap = NO; // 点击通知
    NSDictionary* remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    NSLog(@"%@",remoteNotification);
    if (remoteNotification == NULL) {
        self.tap = NO; // 点击通知
    }else {
        self.tap = YES;
    }
    return YES;
}
- (void)theNetWorkConnectStates {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"-------AFNetworkReachabilityStatusReachableViaWWAN------");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"-------AFNetworkReachabilityStatusReachableViaWiFi------");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [[MessShowView share] showWithMess:@"当前网络不可用"];
                break;
            default:
                break;
        }
    }];
}
- (void)theGuidedView {
    NSLog(@"the hei %f",ScreenHeight);
    NSArray *imgArr ;
    if (ScreenHeight == 480) {
        imgArr = @[@"引导页01 960.png",@"引导页02 960.png",@"引导页03 960.png"];
    }else if (ScreenHeight == 568) {
        imgArr = @[@"引导页01 1136.png",@"引导页02 1136.png",@"引导页03 1136.png"];
    }else if (ScreenHeight == 1334/2) {
        imgArr = @[@"引导页01 1334.png",@"引导页02 1334.png",@"引导页03 1334.png"];
    }else if (ScreenHeight == 2208/3) {
        imgArr = @[@"引导页01 2208.png",@"引导页02 2208.png",@"引导页03 2208.png"];
    }
    guideView = [[GuideView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    [guideView theGuideImg:imgArr];
    [guideView.endbtn addTarget:self action:@selector(endAction) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:guideView];
}
- (void)endAction {
    for (UIView *view in guideView.subviews) {
        [view removeFromSuperview];
    }
    [guideView removeFromSuperview],guideView = nil;
    SelectNearProprieterController *selectProprieter = [[SelectNearProprieterController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:selectProprieter];
    nav.navigationBarHidden = YES;
    self.window.rootViewController = nav;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // [EXT] APP进入后台时，通知个推SDK进入后台
    [GeTuiSdk enterBackground];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    // [EXT] 重新上线
    [self startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
}
- (void)applicationWillTerminate:(UIApplication *)application {
    
}
-(void) stopSdk {
    [GeTuiSdk enterBackground];
}
#pragma mark - 推送部分
#pragma mark - background fetch  唤醒
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    //[5] Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    _deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"deviceToken:%@", _deviceToken);
    // [3]:向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:_deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    // [3-EXT]:如果APNS注册失败，通知个推服务器
    [GeTuiSdk registerDeviceToken:@""];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userinfo {
    // [4-EXT]:处理APN
    NSString *payloadMsg = [userinfo objectForKey:@"payload"];
    if (payloadMsg) {
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], payloadMsg];
    }
}
#pragma mark - 点击通知栏走
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    // [4-EXT]:处理APN
    self.tap = YES;
    NSString *payloadMsg = [userInfo objectForKey:@"payload"];
    NSDictionary *aps = [userInfo objectForKey:@"aps"];
    NSNumber *contentAvailable = aps == nil ? nil : [aps objectForKeyedSubscript:@"content-available"];
    if (payloadMsg && contentAvailable) {
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@, [content-available: %@]", [NSDate date], payloadMsg, contentAvailable];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret {
    NSError *err = nil;
    //[1-1]:通过 AppId、 appKey 、appSecret 启动SDK
    [GeTuiSdk startSdkWithAppId:appID appKey:appKey appSecret:appSecret delegate:self error:&err];
    //[1-2]:设置是否后台运行开关
    [GeTuiSdk runBackgroundEnable:YES];
    // 手机唯一标示符
    NSString *cid =  [GeTuiSdk clientId];
    NSLog(@"%@",cid);
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    [userDefaul setObject:cid forKey:@"cid"];
}
- (void)setDeviceToken:(NSString *)aToken{
    [GeTuiSdk registerDeviceToken:aToken];
}
- (BOOL)setTags:(NSArray *)aTags error:(NSError **)error {
    return [GeTuiSdk setTags:aTags];
}
- (NSString *)sendMessage:(NSData *)body error:(NSError **)error {
    return [GeTuiSdk sendMessage:body error:error];
}
- (void)bindAlias:(NSString *)aAlias {
    [GeTuiSdk bindAlias:aAlias];
}
- (void)unbindAlias:(NSString *)aAlias {
    [GeTuiSdk unbindAlias:aAlias];
}
- (void)testGetClientId {
    NSString *clientId = [GeTuiSdk clientId];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"当前的CID" message:clientId delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}
#pragma mark - GexinSdkDelegate
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId{
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    if (_deviceToken) {
        [GeTuiSdk registerDeviceToken:_deviceToken];
    }
}
#pragma mark - 收到后台推送
- (void)GeTuiSdkDidReceivePayload:(NSString *)payloadId andTaskId:(NSString *)taskId andMessageId:(NSString *)aMsgId fromApplication:(NSString *)appId {
    // [4]: 收到个推消息
    NSData* payload = [GeTuiSdk retrivePayloadById:payloadId];
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
                                              length:payload.length
                                            encoding:NSUTF8StringEncoding];
        NSLog(@"推送信息：%@",payloadMsg);
    }
    NSError *err;
    NSDictionary *messDic ;
    if (payload) {
        messDic = [NSJSONSerialization JSONObjectWithData:payload
                                                  options:NSJSONReadingMutableContainers
                                                    error:&err];
    }
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return;
    }
    //===================================================================================
    //                                  通知
    //===================================================================================
    NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@"1",@"textOne",@"2",@"textTwo", nil];
    //创建通知
    NSNotification *noti =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:noti];
    /********************************/
    if (self.tap == NO) {
//        //定义变量，表示音频文件
//        SystemSoundID soundID;
//        //加载音频文件
//        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[[NSBundle mainBundle]URLForResource:@"xiaoxi" withExtension:@"mp3"], &soundID);
        NSString *lingsheng = [NSUserDefualManager getValueByKey:@"lingsheng"];
        NSString *zhendong = [NSUserDefualManager getValueByKey:@"zhendong"];
        NSLog(@"%@=====%@",lingsheng,zhendong);
        PlaySoundYM *sy = [[PlaySoundYM alloc]initForPlayingSoundEffectWith:@"xiaoxi" Extension:@"mp3"];
        PlaySoundYM *zd = [[PlaySoundYM alloc]initForPlayingVibrate];
        if ([lingsheng isEqualToString:@"1"] && [zhendong isEqualToString:@"1"]) {//铃声加震动
//            AudioServicesPlaySystemSound(soundID);
//            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            [sy play];
            [zd play];
        }else if ([lingsheng isEqualToString:@"0"] && [zhendong isEqualToString:@"1"]) {//震动
//            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            [zd play];
        }else if ([lingsheng isEqualToString:@"1"] && [zhendong isEqualToString:@"0"]) {//铃声
//            AudioServicesPlaySystemSound(soundID);
            [sy play];
        }else {//静音
            
        }
    }
    //
    /********************************/
    if (messDic) {
        if ([messDic isKindOfClass:[NSDictionary class]]) { // 通知退出
            NSString *type = [messDic[@"type"] safeString];
            if ([type isEqualToString:@"LzgRejectLogin"]){
                
                if (self.alertCount == 0) {
                    self.alertCount ++;
                    UIAlertView *aler = [[UIAlertView alloc] initWithTitle:nil message:@"您的账号已在另一台设备上登录,是否重新登录" delegate:self cancelButtonTitle:@"登录" otherButtonTitles:@"退出", nil];
                    [aler show];
                }
                
            }else{
                if (self.tap == NO) {
//                    //定义变量，表示音频文件
//                    SystemSoundID soundID;
//                    //加载音频文件
//                    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[[NSBundle mainBundle]URLForResource:@"xiaoxi" withExtension:@"mp3"], &soundID);
                    
                    NSString *lingsheng = [NSUserDefualManager getValueByKey:@"lingsheng"];
                    NSString *zhendong = [NSUserDefualManager getValueByKey:@"zhendong"];
                    NSLog(@"%@=====%@",lingsheng,zhendong);
                    
                    PlaySoundYM *sy = [[PlaySoundYM alloc]initForPlayingSoundEffectWith:@"xiaoxi" Extension:@"mp3"];
                    PlaySoundYM *zd = [[PlaySoundYM alloc]initForPlayingVibrate];
                    if ([lingsheng isEqualToString:@"1"] && [zhendong isEqualToString:@"1"]) {//铃声加震动
                        //            AudioServicesPlaySystemSound(soundID);
                        //            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                        [sy play];
                        [zd play];
                    }else if ([lingsheng isEqualToString:@"0"] && [zhendong isEqualToString:@"1"]) {//震动
                        //            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                        [zd play];
                    }else if ([lingsheng isEqualToString:@"1"] && [zhendong isEqualToString:@"0"]) {//铃声
                        //            AudioServicesPlaySystemSound(soundID);
                        [sy play];
                    }else {//静音
                        
                    }
                }
                
            }
        }
    }
    /********************************/
    if (self.tap == YES) {
        if (messDic) {
            if ([messDic isKindOfClass:[NSDictionary class]]) {
                NSString *title = [messDic[@"title"] safeString];
                NSString *type = [messDic[@"type"] safeString];
                BOOL doDetail = NO;
                //            订单支付成功或货到付款推送给商家
                
                /*
                 点击通知后push到指定控制器
                 */
                //BossMessagVC *messageVC = [[BossMessagVC alloc]init];
//               UIWindow *window = [[UIApplication sharedApplication]keyWindow];
//                UINavigationController *nav = (UINavigationController *)window.rootViewController;
//                UIViewController *viewController = [nav.viewControllers objectAtIndex:0];
                BossMessagVC *messageVC = [[BossMessagVC alloc] init];
//                [viewController.navigationController pushViewController:messageVC animated:YES];
                BaseTabBarViewController *baseTab = [[BaseTabBarViewController alloc] init];
                [baseTab changeBottomBtnWithIndex:0];
                [[self getCurrentVC] presentViewController:baseTab animated:NO completion:^{
                    self.tap = NO;
                }];
                [self.tabVC.navigationController popToRootViewControllerAnimated:NO];
                [self.tabVC.selectedViewController.navigationController pushViewController:messageVC animated:YES];
                doDetail = YES;
                self.tap = NO;
//                if ([type isEqualToString:@"LzgOrderPaySuccess"]) {
//                    BossMessagVC *messageVC = [[BossMessagVC alloc] init];
//                    //order.todayOrder = 3;
//                    //order.tuisong = @"y"; // 返回
//                    [viewController.navigationController pushViewController:messageVC animated:YES];
//                    doDetail = NO;
//                    self.tap = NO;
//                }else if ([type isEqualToString:@"LzgRemindSupplierPost"]) { // 申请退货推送给商家
//                    BossMessagVC *messageVC = [[BossMessagVC alloc] init];
////                    order.tuisong = @"y"; // 返回
////                    order.tuiHuoManager = YES;
//                    [viewController.navigationController pushViewController:messageVC animated:YES];
//                    doDetail = YES;
//                    self.tap = NO;
//                }else if ([type isEqualToString:@"LzgApplyRefund"]) {  BossMessagVC *messageVC = [[BossMessagVC alloc] init];
//                    [viewController.navigationController pushViewController:messageVC animated:YES];
//                    doDetail = NO;
//                    self.tap = NO;
//                }else if ([type isEqualToString:@"LzgRemindSupplierPost"]){// 云端提醒商家发货
//                    // 调到代发货
//                   BossMessagVC *messageVC = [[BossMessagVC alloc] init];
////                    order.todayOrder = 0;
////                    order.tuisong = @"y"; // 返回
//                    [viewController.navigationController pushViewController:messageVC animated:YES];
//                    doDetail = NO;
//                    self.tap = NO;
//                }

//                if ([type isEqualToString:@"OrderPaySuccessOrPayReceiveToSeller"]) {
//                    OrderViewController *order = [[OrderViewController alloc] init];
//                    order.todayOrder = 3;
//                    order.tuisong = @"y"; // 返回
//                    [[self getCurrentVC] presentViewController:order animated:YES completion:^{
//                        self.tap = NO;
//                    }];
//                    doDetail = NO;
//                    self.tap = NO;
//                }else if ([type isEqualToString:@"ApplyReturnProductToSeller"]) { // 申请退货推送给商家
//                    OrderViewController *order = [[OrderViewController alloc] init];
//                    order.tuisong = @"y"; // 返回
//                    order.tuiHuoManager = YES;
//                    [[self getCurrentVC] presentViewController:order animated:YES completion:^{
//                        self.tap = NO;
//                    }];
//                    doDetail = YES;
//                    self.tap = NO;
//                }else if ([type isEqualToString:@"ChangeMobilephoneToSeller"]) { // 通知退出
//                    doDetail = NO;
//                    self.tap = NO;
//                }else if ([type isEqualToString:@"lanmao_url"]) {
//                    doDetail = NO;
//                    self.tap = NO;
//                }else if ([type isEqualToString:@"CustomerRemindSupplierPost"]){// 客户催促商家发货
//                    doDetail = NO;
//                    self.tap = NO;
//                }else if ([type isEqualToString:@"ServerCustomerRemindSupplierPost"]){// 云端提醒商家发货
//                    // 调到代发货
//                    OrderViewController *order = [[OrderViewController alloc] init];
//                    order.todayOrder = 0;
//                    order.tuisong = @"y"; // 返回
//                    [[self getCurrentVC] presentViewController:order animated:YES completion:^{
//                        self.tap = NO;
//                    }];
//                    doDetail = NO;
//                    self.tap = NO;
//                }
            }
        }
    }   //self.tap == YES
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSLog(@"确定");
        self.alertCount =0;
        MyViewController *myview = [[MyViewController alloc] init];
        [myview loginFirst];
    }else{
        NSLog(@"取消");
        self.alertCount =0;
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        self.window.rootViewController = loginVC;
        NSString *url = [NSString stringWithFormat:lzgLoginOut,[AppData share].username];
        [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
            NSDictionary *dict = result;
            NSString *r = dict[@"r"];
            if ([r isEqualToString:@"T"]) {
                [[AppData share] clearValue];
                [NSUserDefualManager storageValue:@"" forKey:UserName];
                [NSUserDefualManager storageValue:@"" forKey:Psw];
                [AppData share].baseTabVC.redLable.hidden = YES;
                [NSUserDefualManager storageValue:@"0" forKey:@"doLogin"];
                NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults]; // 蓝牙开关状态
                [userDefaul setObject:@"off" forKey:@"switch"];
            }
        }];
    }
}
- (UIViewController *)getCurrentVC {
    UIViewController* activityViewController = nil;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if(window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow *tmpWin in windows) {
            if(tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    NSArray *viewsArray = [window subviews];
    if([viewsArray count] > 0) {
        UIView *frontView = [viewsArray objectAtIndex:0];
        id nextResponder = [frontView nextResponder];
        if([nextResponder isKindOfClass:[UIViewController class]]) {
            activityViewController = nextResponder;
        }else{
            activityViewController = window.rootViewController;
        }
    }
    return activityViewController;
}
@end
